import store from '@/store'
import { createRouter, createWebHistory } from 'vue-router'

import NProgress from 'nprogress'

export const routes = [
  {
    path: '/',
    name: '/',
  },
  {
    path: '/index',
    name: '首页',
    component: () => import('@/views/index'),
    meta: {
      searchable: false,
    },
  },
  {
    path: '/oauth2/authorized',
    name: 'OAuth2授权回调',
    component: () => import('@/views/oauth2/Authorized'),
    props: (route) => ({
      code: route.query.code,
      error: route.query.error,
      error_description: route.query.error_description,
    }),
    meta: {
      searchable: false,
    },
  },
  {
    name: '没有找到',
    path: '/:pathMatch(.*)',
    redirect: '/404',
    meta: {
      searchable: false,
    },
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
  strict: true,
})

NProgress.configure({ showSpinner: false })

const loginIgnore = {
  names: [], //根据路由名称匹配
  paths: ['/oauth2/authorized'], //根据路由fullPath匹配
  // 判断路由是否包含在该配置中
  includes(route) {
    return this.names.includes(route.name) || this.paths.includes(route.path)
  },
}

// 加载路由守卫
router.beforeEach(async (to, from, next) => {
  if (!NProgress.isStarted()) {
    NProgress.start()
  }

  if (to.path == '/') {
    next('/index')
    return
  }

  if (loginIgnore.includes(to)) {
    next()
    return
  }

  if (
    !store.getters.oauth2Token ||
    Object.keys(store.getters.oauth2Token).length === 0
  ) {
    store.dispatch('oauth2Client/gotoAuthCenter')
    return
  }

  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
